<!DOCTYPE html>
<html lang="zh">

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
	<title>授权管理 - {$SystemName}</title>
	<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-touch-fullscreen" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="default">
	<link rel="stylesheet" type="text/css" href="/css/materialdesignicons.min.css">
	<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
	<!--表格插件css-->
	<link rel="stylesheet" href="/js/bootstrap-table/bootstrap-table.min.css">
	<link rel="stylesheet" type="text/css" href="/css/style.min.css">
	<link rel="stylesheet" type="text/css" href="/js/jquery-confirm/jquery-confirm.min.css">
	<link rel="stylesheet" type="text/css" href="/js/bootstrap-datepicker/bootstrap-datepicker3.min.css">
</head>

<body>

	<div class="container-fluid">
		<div class="alert alert-warning">
			请注意! 暂停颁发只能阻止用户领取新的令牌，暂停后用户无法继续领取新的令牌，但是可以继续使用已经领取的令牌。
		</div>
		<div class="modal fade" id="add" tabindex="-1" aria-labelledby="addLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<h6 class="modal-title" id="addLabel">添加授权</h6>
					</div>
					<div class="modal-body">
						<div class="input-group mb-3">
							<span class="input-group-text">邮箱</span>
							<input type="email" class="form-control" placeholder="xxx@example.com" aria-label="标识"
								id="add_email">
						</div>
						<div class="input-group mb-3">
							<span class="input-group-text">到期时间</span>
							<input type="text" class="form-control" placeholder="到期时间" aria-label="时间"
								data-provide="datepicker" data-autoclose="true" id="add_end">
						</div>
						<div class="input-group mb-3">
							<span class="input-group-text">权限</span>
							<select class="form-control selectpicker" name="add_qx" id="add_qx" tabindex="null">
								{foreach $permission as $key => $vo}
								<option value="{$vo['id']}">{$vo["Identifier"]}{if
									$vo["Remark"]!=""}({$vo["Remark"]}){/if}</option>
								{/foreach}
							</select>
							<button type="button" class="btn btn-primary" id="add_qx_btn">添加权限</button>
						</div>
						<div class="mb-3">
							<table class="table table-hover">
								<thead>
									<tr>
										<th>#</th>
										<th>标识</th>
										<th>操作</th>
									</tr>
								</thead>
								<tbody id="qx_list">
								</tbody>
							</table>
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
						<button type="button" class="btn btn-primary" onclick="add()">完成</button>
					</div>
				</div>
			</div>
		</div>
		<div class="modal fade" id="Modify" tabindex="-1" aria-labelledby="ModifyLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<h6 class="modal-title" id="ModifyLabel">授权设置</h6>
					</div>
					<div class="modal-body">
						<div class="input-group mb-3">
							<input type="text" class="form-control" placeholder="主键" aria-label="主键" disabled id="fid">
						</div>
						<div class="input-group mb-3">
							<span class="input-group-text">到期时间</span>
							<input type="text" class="form-control" placeholder="到期时间" aria-label="时间"
								data-provide="datepicker" data-autoclose="true" id="set_end">
						</div>
						<div class="input-group mb-3">
							<span class="input-group-text">权限</span>
							<select class="form-control selectpicker" name="set_qx" id="set_qx" tabindex="null">
								{foreach $permission as $key => $vo}
								<option value="{$vo['id']}">{$vo["Identifier"]}{if
									$vo["Remark"]!=""}({$vo["Remark"]}){/if}</option>
								{/foreach}
							</select>
							<button type="button" class="btn btn-primary" id="set_qx_btn">添加权限</button>
						</div>
						<div class="mb-3">
							<table class="table table-hover">
								<thead>
									<tr>
										<th>#</th>
										<th>标识</th>
										<th>操作</th>
									</tr>
								</thead>
								<tbody id="qx_lists">
								</tbody>
							</table>
						</div>
						<div class="form-check form-switch">
							<input class="form-check-input" type="checkbox" role="switch" id="status">
						</div>
					</div>

					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
						<button type="button" class="btn btn-primary" onclick="set()">保存修改</button>
					</div>
				</div>
			</div>
		</div>


		<div class="row">

			<div class="col-lg-12">
				<div class="card">
					<header class="card-header">
						<div class="card-title">授权管理</div>
					</header>
					<div class="card-body">
						<div id="toolbar" class="toolbar-btn-action">
							<button id="btn_add" type="button" class="btn btn-primary me-1">
								<span class="mdi mdi-plus" aria-hidden="true"></span>新增
							</button>
							<button id="btn_true" type="button" class="btn btn-success me-1">
								<span class="mdi mdi-check" aria-hidden="true"></span>启用
							</button>
							<button id="btn_false" type="button" class="btn btn-warning me-1">
								<span class="mdi mdi-block-helper" aria-hidden="true"></span>暂停
							</button>
						</div>
						<table id="table"></table>

					</div>
				</div>
			</div>

		</div>

	</div>
	<script type="text/javascript" src="/js/jquery.min.js"></script>
	<script type="text/javascript" src="/js/popper.min.js"></script>
	<script type="text/javascript" src="/js/bootstrap.min.js"></script>
	<script type="text/javascript" src="/js/main.min.js"></script>
	<!--表格插件js-->
	<script src="/js/bootstrap-table/bootstrap-table.js"></script>
	<script src="/js/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
	<script type="text/javascript" src="/js/lyear-loading.js"></script>
	<script type="text/javascript" src="/js/bootstrap-notify.min.js"></script>
	<script type="text/javascript" src="/js/jquery-confirm/jquery-confirm.min.js"></script>
	<script type="text/javascript" src="/js/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
	<script type="text/javascript" src="/js/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script>
	<script>
		const qx_list = [];
		const qx_lists = [];
		function clear_qx(type, id, obj) {
			if (type == 0) {
				qx_list.splice(qx_list.indexOf(id), 1);
			} else {
				qx_lists.splice(qx_lists.indexOf(id), 1);
			}
			$(obj).parent().parent().remove();
		}
		$(function () {
			$("#btn_true").on("click", function () { edit(0) });
			$("#btn_false").on("click", function () { edit(1) });
			$("#btn_add").on("click", function () {
				$("#add").modal('show'), qx_list.length = 0;
				$("#qx_list").html("");
			});
			$("#add_qx_btn").on("click", function () {
				if (qx_list.indexOf($("#add_qx").val()) !== -1) return notify("添加失败", "权限已存在", "error");
				qx_list.push($("#add_qx").val());
				$("#qx_list").append(`<tr>
					<td>${$("#add_qx").val()}</td>
					<td>${$("#add_qx option:selected").text()}</td>
					<td><span class="badge bg-danger" onclick="clear_qx(0,${$("#add_qx").val()},this)">删除</span></td>
				</tr>`)
			});
			$("#set_qx_btn").on("click", function () {
				if (qx_lists.indexOf($("#set_qx").val()) !== -1) return notify("添加失败", "权限已存在", "error");
				qx_lists.push($("#set_qx").val());
				$("#qx_lists").append(`<tr>
					<td>${$("#set_qx").val()}</td>
					<td>${$("#set_qx option:selected").text()}</td>
					<td><span class="badge bg-danger" onclick="clear_qx(0,${$("#set_qx").val()},this)">删除</span></td>
				</tr>`)
			});
			function edit(status) {
				let data = {
					ids: $('#table').bootstrapTable('getSelections').map(item => item.id),
					content: { status }
				}
				const l = $("#table").lyearloading({
					opacity: 0.1,
					backgroundColor: '#ccc',
					textColorClass: 'text-success',
					spinnerColorClass: 'text-success',
					spinnerSize: 'lg',
					zindex: 9999,
				});
				$.ajax({
					type: "POST",
					url: "?action=set",
					data,
					dataType: "json",
					success: function (data) {
						l.hide();
						if (data.code == 200) {
							$("#Modify").modal('hide');
							notify("修改授权", data.msg, "success");
							$("#table").bootstrapTable('refresh');
						} else {
							notify("修改授权", data.msg, "error");
						}
					},
					error: function (data) {
						l.hide();
						notify("修改授权", "修改授权失败，请稍后再试！", "error");
					}
				})
			}
		})
		function add() {
			if (!(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/).test($("#add_email").val())) return notify("添加失败", "邮箱格式错误", "error");
			let data = {
				permission_ider: qx_list,
				email: $("#add_email").val(),
				end_time: $("#add_end").val(),
			}
			const l = $("#add").lyearloading({
				opacity: 0.1,
				backgroundColor: '#ccc',
				textColorClass: 'text-success',
				spinnerColorClass: 'text-success',
				spinnerSize: 'lg',
				zindex: 9999,
			});
			$.ajax({
				type: "POST",
				url: "?action=add",
				data,
				dataType: "json",
				success: function (data) {
					l.hide();
					if (data.code == 200) {
						$("#add").modal('hide');
						notify("添加授权", data.msg, "success");
						$("#table").bootstrapTable('refresh');
						$("#add_email").val("");
						$("#add_end").val("");
						$("#qx_list").html("");
					} else {
						notify("添加授权", data.msg, "error");
					}
				},
				error: function (data) {
					l.hide();
					notify("添加授权", "添加授权失败，请稍后再试！", "error");
				}
			})
		}
		function set() {
			let data = {
				ids: [$("#fid").val()],
				content: {
					ExpirationTime: $("#set_end").val(),
					status: $('#status').prop('checked') ? 0 : 1
				},
				permission_ider: qx_lists,
			}
			console.log(data)
			const l = $("#Modify").lyearloading({
				opacity: 0.1,
				backgroundColor: '#ccc',
				textColorClass: 'text-success',
				spinnerColorClass: 'text-success',
				spinnerSize: 'lg',
				zindex: 9999,
			});
			$.ajax({
				type: "POST",
				url: "?action=set",
				data,
				dataType: "json",
				success: function (data) {
					l.hide();
					if (data.code == 200) {
						$("#Modify").modal('hide');
						notify("修改授权", data.msg, "success");
						$("#table").bootstrapTable('refresh');
					} else {
						notify("修改授权", data.msg, "error");
					}
				},
				error: function (data) {
					l.hide();
					notify("修改授权", "修改授权失败，请稍后再试！", "error");
				}
			})
		}
		/**
		 * 分页相关的配置
		 **/
		const pagination = {
			// 分页方式：[client] 客户端分页，[server] 服务端分页
			sidePagination: "server",
			// 初始化加载第一页，默认第一页
			pageNumber: 1,
			// 每页的记录行数
			pageSize: 10,
			// 可供选择的每页的行数 - (亲测大于1000存在渲染问题)
			pageList: [5, 10, 25, 50, 100],
			// 在上百页的情况下体验较好 - 能够显示首尾页
			paginationLoop: true,
			// 展示首尾页的最小页数
			paginationPagesBySide: 2
		};

		/**
		 * 按钮相关配置
		 **/
		const button = {
			// 按钮的类
			buttonsClass: 'default',
			// 类名前缀
			buttonsPrefix: 'btn'
		}

		/**
		 * 图标相关配置
		 **/
		const icon = {
			// 图标前缀
			iconsPrefix: 'mdi',
			// 图标大小
			iconSize: 'mini',
			// 图标的设置
			icons: {
				paginationSwitchDown: 'mdi-door-closed',
				paginationSwitchUp: 'mdi-door-open',
				refresh: 'mdi-refresh',
				toggleOff: 'mdi-toggle-switch-off',
				toggleOn: 'mdi-toggle-switch',
				columns: 'mdi-table-column-remove',
				detailOpen: 'mdi-plus',
				detailClose: 'mdi-minus',
				fullscreen: 'mdi-monitor-screenshot',
				search: 'mdi-table-search',
				clearSearch: 'mdi-trash-can-outline'
			}
		};

		/**
		 * 表格相关的配置
		 **/
		const table = {
			classes: 'table table-bordered table-hover table-striped lyear-table',
			// 请求地址
			url: '?action=list',
			// 唯一ID字段
			uniqueId: 'id',
			// 每行的唯一标识字段
			idField: 'id',
			// 是否启用点击选中行
			clickToSelect: true,
			// 是否显示详细视图和列表视图的切换按钮(clickToSelect同时设置为true时点击会报错)
			// showToggle: true,
			// 请求得到的数据类型
			dataType: 'json',
			// 请求方法
			method: 'post',
			// 工具按钮容器
			toolbar: '#toolbar',
			// 是否分页
			pagination: true,
			// 是否显示所有的列
			showColumns: true,
			//开启搜索输入框
			search: true,
			// 搜索时是否去除空格
			trimOnSearch: true,
			// 是否显示刷新按钮
			showRefresh: true,
			// 显示图标
			showButtonIcons: true,
			// 显示文本
			showButtonText: false,
			// 显示全屏
			showFullscreen: true,
			// 开关控制分页
			showPaginationSwitch: true,
			// 总数字段
			totalField: 'total',
			// 当字段为 undefined 显示
			undefinedText: '-',
			// 排序方式
			sortOrder: "asc",
			...icon,
			...pagination,
			...button
		};

		/**
		 * 用于演示的列信息
		 **/
		const columns = [{
			field: 'example',
			checkbox: true,
			// 列的宽度
			width: 5,
			// 宽度单位
			widthUnit: 'rem'
		}, {
			field: 'id',
			title: '编号',
			// 使用[align]，[halign]和[valign]选项来设置列和它们的标题的对齐方式。
			// h表示横向，v标识垂直
			align: 'center',
			// 是否作为排序列
			sortable: true,
			// 当列名称与实际名称不一致时可用
			sortName: 'sortId',
			switchable: false,
			// 列的宽度
			width: 8,
			// 宽度单位
			widthUnit: 'rem'
		}, {
			field: 'email',
			align: 'center',
			title: '邮箱',
		}, {
			field: 'permission_ider',
			align: 'center',
			title: '权限',
			formatter: function (value, row, index) {
				if (value == null || value.length == 0) return '-';
				return `<a href="javascript:void(0);" >(${JSON.parse(value).length})</a>`;
			},
			events: {
				'click a': function (event, value, row, index) {
					event.stopPropagation();
					editUser(row)
				}
			}
		}, {
			field: 'AuthorizationTime',
			align: 'center',
			title: '令牌颁发时间'
		}, {
			field: 'ExpirationTime',
			align: 'center',
			title: '授权到期时间',
			formatter: function (value, row, index) {
				return value.split(' ')[0];
			},
		}, {
			field: 'UsageCount',
			align: 'center',
			title: '使用次数'
		}, {
			field: 'creat_time',
			align: 'center',
			title: '创建时间'
		}, {
			field: 'status',
			title: '状态',
			formatter: function (value, row, index) {
				var value = "";
				if (row.status == '0') {
					value = '<span class="badge bg-success">正常</span>';
				} else if (row.status == '1') {
					value = '<span class="badge bg-danger">禁用</span>';
				} else {
					value = '<span class="badge bg-secondary">未知</span>';
				}
				return value;
			}
		}, {
			field: 'operate',
			title: '操作',
			formatter: btnGroup,  // 自定义方法
			events: {
				'click .edit-btn': function (event, value, row, index) {
					event.stopPropagation();
					editUser(row);
				}
			}
		}];

		// 自定义操作按钮
		function btnGroup() {
			let html =
				'<a href="#!" class="btn btn-sm btn-default me-1 edit-btn" title="编辑" data-bs-toggle="tooltip" ><i class="mdi mdi-pencil"></i></a>';
			return html;
		}

		// 操作方法 - 编辑
		function editUser(row) {
			const l = $("body").lyearloading({
				opacity: 0.1,
				backgroundColor: '#ccc',
				textColorClass: 'text-success',
				spinnerColorClass: 'text-success',
				spinnerSize: 'lg',
				zindex: 9999,
			});
			$.ajax({
				url: '?action=get_user_info',
				type: 'post',
				data: {
					id: row.id
				},
				success: function (data) {
					l.destroy();
					if (data.code == 200) {
						$("#Modify").modal('show');
						$("#fid").val(row.id);
						$("#set_end").val(data.data.ExpirationTime.split(" ")[0])
						qx_lists.length = 0;
						qx_lists.push(...data.data.permission_ider);
						$("#qx_lists").html("");
						data.data.permission.forEach(per => {
							$("#qx_lists").append(`<tr>
					<td>${per.id}</td>
					<td ${per.status == 0 ? "" : "class='text-danger'"}>${per.Identifier}${per.Remark == "" ? "" : "(" + per.Remark + ")"}</td>
					<td><span class="badge bg-danger" onclick="clear_qx(1,${$("#add_qx").val()},this)">删除</span></td>
				</tr>`)
						});
						$('#status').prop('checked', data.data.status == 0 ? true : false);
					}
				}
			})
			// $("#Modify").modal('show');
			// $("#fid").val(row.id);
			// $("#Identifier").val(row.Identifier);
			// $("#Remark").val(row.Remark);

		}

		$('#table').bootstrapTable({
			...table,
			// 自定义的查询参数
			queryParams: function (params) {
				return {
					// 每页数据量
					limit: params.limit,
					// sql语句起始索引
					offset: params.offset,
					page: (params.offset / params.limit) + 1,
					// 排序的列名
					sort: params.sort,
					// 排序方式 'asc' 'desc'
					sortOrder: params.order,
					// 搜索
					search: params.search,
				};
			},
			columns,
			onLoadSuccess: function (data) {
				$("[data-bs-toggle='tooltip']").tooltip();
			}
		});
		function notify(title, message, type) {
			if (window.parent && window.parent !== window) if (typeof window.parent.notify === 'function') return window.parent.notify(title, message, type);
			if (typeof $.notify != 'function') return;
			switch (type) {
				case 'success':
					icon = "mdi mdi-check-all"
					type = 'success';
					break;
				case 'warning':
					icon = "mdi mdi-alert-circle"
					type = 'warning';
					break;
				case 'error':
					icon = "mdi mdi-close-octagon-outline"
					type = 'danger';
					break;
				default:
					icon = "mdi mdi-information-outline"
					type = 'info';
			}
			$.notify({
				icon: 'mdi mdi-alert',
				title,
				message,
				url: '',
				target: '_blank'
			}, {
				type,
				allow_dismiss: true,
				newest_on_top: true,
				placement: {
					from: 'top',
					align: 'right'
				},
				offset: {
					x: 20,
					y: 20
				},
				spacing: 10,
				z_index: 1031,
				delay: 3000,
				animate: {
					enter: 'animate__animated animate__fadeInDown',
					exit: 'animate__animated animate__fadeOutRight'
				},
			});
		}
	</script>
</body>

</html>